﻿var bitadv = "autosense";
var tcount = 0;
function unitTest(showcontent) {
    document.getElementById("test1").innerHTML = document.getElementById("test1").innerHTML + showcontent;
};
(function (winobj, winvarobj) {
    //---------------------------------对象缩编定义区-------------------------------------------
    var win = window;
    var isIE = (!!window.ActiveXObject || "ActiveXObject" in window) ? true : false;
    var dom = win.document;
    var addEvent = win.addEventListener ? win.addEventListener : win.attachEvent;
    var _$ = function (id) { return dom.getElementById(id); };
    //配置挂载全局对象属性
    if (!winobj[winvarobj]) {
        winobj[winvarobj] = function () { };
    }
    var globalwin = winobj[winvarobj];
    var advhostpage = null;
    var advbase = null;
    var user = null;
    var nasConfig = null;
    var advPositionSet = null;
    var scriptId = "nas-js-";
    var generateId = "";
    var posId = "nas-pos-";
    var testScrollTimespan = 200;
    var testHeartTimespan = 350;
    var maxLeaveTimespan = 300000;//5分钟
    var pageHeartTimespan = 10000;//页面10秒钟心跳间隔
    var adHeartTimespan = 5000;//广告展示心跳间隔5秒
    var adHeartTotal = 5;//广告展示心跳次数
    var adRequestUrlDmain = "http://autosense.bitauto.com/service";
    //------------------------------窗体级别定义区---------------------------------------------
    if (!globalwin.inited) {
        globalwin.inited = true;
        //基础对象
        advbase = {
            guid: function () {
                var guid = "";
                for (var i = 1; i <= 32; i++) {
                    var n = Math.floor(Math.random() * 16.0).toString(16);
                    guid += n;
                    if ((i == 8) || (i == 12) || (i == 16) || (i == 20))
                        guid += "-";
                }
                return guid;
            },
            getComputedStyle: function (domobj) {
                var coordinate = { width: 0, height: 0 };
                if (win.getComputedStyle) {
                    var styleobj = win.getComputedStyle(domobj, null);
                    coordinate.height = styleobj.height;
                    coordinate.width = styleobj.width;
                } else {
                    coordinate.height = (domobj.currentStyle.height != "auto") ? domobj.currentStyle.height : domobj.offsetHeight;
                    coordinate.width = (domobj.currentStyle.width != "auto") ? domobj.currentStyle.width : domobj.offsetWidth;
                }
                return coordinate;
            },
            formatDate: function (dateobj) {
                return dateobj.getFullYear() + "-" + (dateobj.getMonth() + 1) + "-" + dateobj.getDay() + " " + dateobj.getHours() + ":" + dateobj.getMinutes() + ":" + dateobj.getSeconds() + " " + dateobj.getMilliseconds();
            },
            getClientInfo: function () {
                var brower = ''; //浏览器类型
                var screenWidth = window.screen.width; //分辨率 宽度
                var screenHeight = window.screen.height; //分辨率 高度
                var bitadvbrower = {};
                var ua = navigator.userAgent.toLowerCase();
                //alert(ua);
                var s;
                if (isIE) {
                    s = ua.match(/msie ([\d.]+)/);
                    s ? (bitadvbrower.ie = s[1]) : (bitadvbrower.ie = "11");
                    //alert(bitadvbrower.ie)
                }
                else {
                    (s = ua.match(/firefox\/([\d.]+)/)) ? bitadvbrower.firefox = s[1] :
                   (s = ua.match(/chrome\/([\d.]+)/)) ? bitadvbrower.chrome = s[1] :
                   (s = ua.match(/opera.([\d.]+)/)) ? bitadvbrower.opera = s[1] :
                   (s = ua.match(/version\/([\d.]+).*safari/)) ? bitadvbrower.safari = s[1] : 0;
                }
                //alert(bitadvbrower)
                if (bitadvbrower.ie) brower = 'IE: ' + bitadvbrower.ie;
                if (bitadvbrower.firefox) brower = 'Firefox: ' + bitadvbrower.firefox;
                if (bitadvbrower.chrome) brower = 'Chrome: ' + bitadvbrower.chrome;
                if (bitadvbrower.opera) brower = 'Opera: ' + bitadvbrower.opera;
                if (bitadvbrower.safari) brower = 'Safari: ' + bitadvbrower.safari;
                return {
                    brower: brower
                    , screenWidth: screenWidth
                    , screenHeight: screenHeight
                };
            },
            deleteVar: function (globalvarname) {
                if (globalwin.advhostpage.candelete) {
                    try {
                        delete win[globalvarname];
                    }
                    catch (ex) {
                        globalwin.advhostpage.candelete = false;
                        win[globalvarname] = null;
                    };
                } else {
                    win[globalvarname] = null;
                };
            },
            isInstance:function(varobj){
                if (typeof (varobj) == "undefined")
                    return false
                return true;
            }
        };
        globalwin.advbase = advbase;
       
        //页面对象初始化
        advhostpage = {
            pageid: "",
            candelete: true,
            pageFail: false,
            pageHeartbeatStop: false,
            pageHeart:true,
            pageRequestTime: new Date,
            lastHeartTime:new Date,
            referer: win.document.referrer,
            location: win.location.href,
            href: win.location.href,
            isscolling: false,
            pageLeaveTime: null,
            pageLeaveTimespan: 0,
            //页面加载的标识是否已经发出
            pageRequestInfoSended:false,
            //鼠标横坐标
            mx: 0,
            //鼠标纵坐标
            my: 0,
            //广告展示信息发送
            sendAdMsg: function () {

                //tcount++;
                //unitTest("<br>3-tcount:" + tcount);
                //alert("发送区")
                if (globalwin.user.isleav)//离开状态不检测展示状态
                    return;
                if (advhostpage.isscolling)//滚动状态不检测展示状态
                    return;
                //alert("广告监测区")
                globalwin.advPositionSet.checkwrap();
                globalwin.advPositionSet.decideShow();
                var arr = globalwin.advPositionSet.getViewAds();
                var viewurl = "&pageid=" + advhostpage.pageid + "&userid=" + globalwin.user.userid + "&mx=" + advhostpage.mx + "&my=" + advhostpage.my;
                for (var i = 0; i < arr.length; i++) {
                    if (!arr[i].heartbeat) continue;//无心跳设置的广告位，跳过
                        if (arr[i].issend) {
                            var currenttime = new Date;
                            if ((currenttime.getTime() - arr[i].lastheartsendtime.getTime()) >adHeartTimespan) {
                                viewurl = globalwin.nasConfig.urlitem[6].viewAdHeartSrc + "?lt=7" + viewurl + "&posid=" + arr[i].generateId + "&adTimespan=" + arr[i].adTimespan + "&wl=" + arr[i].wraplegal + "&ct=" + globalwin.advbase.formatDate(new Date);
                                arr[i].lastheartsendtime = new Date;
                                //控制心跳次数
                                arr[i].hearttotal = arr[i].hearttotal - 1;
                                if (arr[i].hearttotal==0)                                
                                    arr[i].heartbeat = false;                               
                                advhostpage.loadJs(viewurl, function () { }, null, scriptId, null);
                            }
                        }
                        else {
                            arr[i].issend = true;
                            arr[i].lastheartsendtime = new Date;
                            viewurl = globalwin.nasConfig.urlitem[1].viewAdsSrc + "?lt=4" + viewurl + "&posid=" + arr[i].generateId + "&wl=" + arr[i].wraplegal + "&ct=" + globalwin.advbase.formatDate(new Date);
                            advhostpage.loadJs(viewurl, function () { }, null, scriptId, null);
                        };

                        //unitTest("<br>4-url:" + viewurl);
                    //unitTest("<br>5-adx:" + arr[i].x + "-ady:" + arr[i].y);

                };

            },
            heartbeat: function () {
                if (advhostpage.pageFail) return;//页面失效，停止心跳
                //alert("心跳函数");
                if (!advhostpage.isscolling) {
                    //    alert("发送小心");
                    advhostpage.sendAdMsg();
                }
                setTimeout(advhostpage.heartbeat, testHeartTimespan);
                var currenttime = new Date;
                if (globalwin.user.isleave&& ((currenttime.getTime() - advhostpage.pageLeaveTime.getTime()) > maxLeaveTimespan)) {
                    var closeurl = globalwin.nasConfig.urlitem[2].leaveSrc + "?lt=6&pageid=" + advhostpage.pageid + "&userid=" + globalwin.user.userid + "&ct=" + globalwin.advbase.formatDate(new Date);
                    advhostpage.loadJs(closeurl, function () { }, null, scriptId, null);
                    advhostpage.pageFail = true;
                };
                if (!advhostpage.pageHeart) return;
                var currenttime = new Date;
                if (currenttime.getTime() - globalwin.advhostpage.lastHeartTime.getTime() > pageHeartTimespan) {
                    var hearturl = globalwin.nasConfig.urlitem[7].pageHeartSrc + "?lt=8&pageid=" + advhostpage.pageid + "&userid=" + globalwin.user.userid + "&ct=" + globalwin.advbase.formatDate(new Date);
                    advhostpage.loadJs(hearturl, function () { }, null, scriptId, null);
                    globalwin.advhostpage.lastHeartTime = new Date;
                };
            },
            //打开页面
            pageRequest: function () {
                var brower = globalwin.advbase.getClientInfo();
                var requesturl = globalwin.nasConfig.urlitem[4].pageViewSrc + "?lt=3&pageid=" + advhostpage.pageid + "&userid=" + globalwin.user.userid + "&location=" + globalwin.advhostpage.location + "&referer=" + globalwin.advhostpage.referer + "&bt=" + brower.brower + "&bw=" + brower.screenWidth + "&bh=" + brower.screenHeight + "&ct=" + globalwin.advbase.formatDate(globalwin.advhostpage.pageRequestTime);
                advhostpage.loadJs(requesturl, function () { }, null, scriptId, null);
            },
            //页面关闭或者刷新
            pageClose: function () {
                var closeurl = globalwin.nasConfig.urlitem[5].pageCloseSrc + "?lt=5&pageid=" + advhostpage.pageid + "&userid=" + globalwin.user.userid + "&ct=" + globalwin.advbase.formatDate(new Date);
                advhostpage.loadJs(closeurl, function () { }, null, scriptId, null);
            },
            //页面滚动
            pageScroll: function () {
                //每隔一秒检测一次是否在滚动
                if (!advhostpage.isscolling) {
                    setTimeout(function () {
                        advhostpage.isscolling = false;
                        globalwin.advPositionSet.advs.forEach(function (ad) {
                            ad.lasttime = new Date;
                        }, this);
                    }, testScrollTimespan);
                    advhostpage.isscolling = true;
                    globalwin.advPositionSet.resetLastTime();
                };
            },
            pageBlur: function () {
                //  globalwin.user.isleave = true;
                advhostpage.pageLeaveTime = new Date;
            },
            pageFocus: function () {
                globalwin.user.isleave = false;
                if (advhostpage.pageLeaveTime)
                    advhostpage.pageLeaveTimespan = (new Date) - advhostpage.pageLeaveTime.getTime();
            },
            loadJs: function (url, callback, charset, id, wrapid) {
                if (_$(id)) {
                    var jsnode = _$(id);
                    try { jsnode.parentNode.removeChild(jsnode); }
                    catch (err) { }
                }
                var scriptText = dom.createElement("script");
                scriptText.type = "text/javascript";
                if (id) scriptText.id = id;
                if (charset) scriptText.charset = charset;
                if (scriptText.readyState) {
                    scriptText.onreadystatechange = function () {
                        if (scriptText.readyState == "loaded" || scriptText.readyState == "complete") {
                            scriptText.onreadystatechange = null;
                            if (callback) callback();
                        }
                    };
                }
                else {
                    scriptText.onload = function () {
                        if (callback) callback();
                    };
                }
                scriptText.src = url;
                if (_$(wrapid)) {
                    _$(wrapid).appendChild(scriptText);
                }
                else
                    dom.body.appendChild(scriptText);
            },
            getMouseXY: function (ev) {
                ev = ev || win.event;
                if (ev.pageX || ev.pageY) {
                    globalwin.advhostpage.mx = ev.pageX, globalwin.advhostpage.my = ev.pageY;
                }
                else {
                    globalwin.advhostpage.mx = ev.clientX + document.body.scrollLeft - document.body.clientLeft,
                   globalwin.advhostpage.my = ev.clientY + document.body.scrollTop - document.body.clientTop
                };

                //unitTest("mx:" + globalwin.advhostpage.mx + "--my:" + globalwin.advhostpage.my);

            }
        };
        advhostpage.pageid = globalwin.advbase.guid();
        globalwin.advhostpage = advhostpage;
        //用户对象
        user = {
            userid: "",
            //是否离开了窗体
            isleave: false,
            //获取指定名称的cookie的值  
            getCookie: function (cookieName) {
                var arrStr = dom.cookie.split("; ");
                if (arrStr) {
                    for (var i = 0; i < arrStr.length; i++) {
                        var temp = arrStr[i].split("=");
                        if (temp[0] == cookieName)
                            return unescape(temp[1]);
                    }
                } else
                    return "no id";
            },
            setCookie: function (cookieName, val) {
                var exdate = new Date();
                dom.cookie = cookieName + "=" + encodeURIComponent(val) + ";max-age=315360000;domain=" + win.document.domain + ";path=/";
            },
            inituser: function () {
                user.userid = user.getCookie("userid");
                if (!user.userid) {
                    user.setCookie("userid", globalwin.advbase.guid());
                    user.userid = user.getCookie("userid");
                }
            }
        };
        globalwin.user = user;
        //广告业务配置对象
        nasConfig = {
            //外部配置项userid、pageid、posid、referurl、unionid、siteid、adnum、type、titlelen、contentlen
            configitem: [{ name: "autosense_uid", val: "" }, { name: "autosense_adsiteid", val: "" }, { name: "autosense_width", val: "" }, { name: "autosense_height", val: "" }, { name: "autosense_arraytype", val: "" }, { name: "autosense_border", val: "" }, { name: "autosense_headbj", val: "" }, { name: "autosense_headtitle", val: "" }, { name: "autosense_contentbj", val: "" }, { name: "autosense_contenttitle", val: "" }, { name: "autosense_contenttext", val: "" }, { name: "autosense_contentlink", val: "" }, { name: "autosense_contentkeyword", val: "" }, { name: "autosense_contentlen", val: "" }, { name: "autosense_isshowhead", val: "" }, { name: "autosense_cbid", val: "" }, { name: "autosense_cityid", val: "" }, { name: "autosense_adnum", val: "" }, { name: "autosense_heartbeat", val: "false" }, { name: "autosense_mrepeate", val: "0" }],
            kv: new Object,
            //需要使用url
            urlitem: [{ iframeSrc: adRequestUrlDmain + "/getad.ashx" }, { viewAdsSrc: adRequestUrlDmain + "/log.ashx" }, { leaveSrc: adRequestUrlDmain + "/log.ashx" }, { firstLoadAdSrc: adRequestUrlDmain + "/log.ashx" }, { pageViewSrc: adRequestUrlDmain + "/log.ashx" }, { pageCloseSrc: adRequestUrlDmain + "/log.ashx" }, { viewAdHeartSrc: adRequestUrlDmain + "/log.ashx" }, { pageHeartSrc: adRequestUrlDmain + "/log.ashx" }],
            //载入配置
            loadConfig: function () {
                var configitems = nasConfig.configitem;
                for (var i = 0; i < configitems.length; i++) {
                    if (globalwin.advbase.isInstance(win[configitems[i].name])) {
                        configitems[i].val = win[configitems[i].name];
                        nasConfig.kv[configitems[i].name] = configitems[i].val;
                        globalwin.advbase.deleteVar(configitems[i].name);
                    };
                };
            }
        };
        globalwin.nasConfig = nasConfig;
        advPositionSet = {
            advs: new Array(),
            isReset:false,
            push: function (advobj) {
                advPositionSet.advs.push(advobj);
            },
            checkwrap: function () {
                for (var i = 0; i < advPositionSet.advs.length; i++) {
                    advPositionSet.advs[i].checkwrap(advPositionSet.advs[i].advdomid, advPositionSet.advs[i]);
                }
            },
            resetLastTime: function () {
                for (var i = 0; i < advPositionSet.advs.length; i++) {
                    advPositionSet.advs[i].lasttime = new Date;
                };
            },
            decideShow: function () {
                for (var i = 0; i < advPositionSet.advs.length; i++) {
                    if (advhostpage.isscolling)//保证滚动状态下不检测展示
                        return;
                    var target = advPositionSet.advs[i];
                    if (!target.heartbeat) return;//不进行心跳的广告不检查
                    var zeroy = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;
                    var zerox = document.documentElement.scrollLeft || window.pageXOffset || document.body.scrollLeft;
                    //完全展示
                    //由于ajax请求会高变部分元素高宽，需要重新即时计算坐标
                    var xy = target.getXY(dom.getElementById(target.advdomid));
                    target.x = xy.x;
                    target.y = xy.y;
                    //unitTest("<br>--->>show==zerox:" + zerox + "-zeroy:" + zeroy);
                    //unitTest("<br>--->>show==target.x:" + target.x + "-target.y:" + target.y);
                    //unitTest("<br>--->>show==targetMW:" + (target.x + target.advwidth) + "-targetMH:" + (target.y + target.advheight));
                    //unitTest("<br>--->>show==zeroMW:" + (zerox + window.screen.availWidth) + "-zeroMH:" + (zeroy + window.screen.availHeight));
                    //alert("px:" + target.x + "-py:" + target.y + "---zerox:" + zerox + "-zeroy:" + zeroy + "--h:" + (zeroy + window.screen.availHeight));
                    target.isview = false;
                    if ((target.x >= zerox) && (target.y >= zeroy) && ((target.x + target.advwidth) <= (zerox + window.screen.availWidth)) && ((target.y + target.advheight) <= (zeroy + window.screen.availHeight))) {
                        target.isview = true;
                        if (target.viewcount == 0) {
                            target.lasttime = new Date;
                            target.firsttime = new Date;
                        };
                        target.viewcount++;
                        var currenttime = new Date;
                        target.adTimespan = currenttime.getTime() - target.lasttime.getTime();

                        //unitTest("<br>full");

                    }
                    else {
                        //计算4个1/3要点的位置，任何一个要点在屏幕内都视为展现
                        var isfind = false;
                        var xcell = target.advwidth / 3;
                        var ycell = target.advheight / 3;
                        var points = [{ x: target.x + xcell, y: target.y + ycell }, { x: target.x + 2 * xcell, y: target.y + ycell }, { x: target.x + xcell, y: target.y + 2 * ycell }, { x: target.x + 2 * xcell, y: target.y + 2 * ycell }];
                        for (var i = 0; i < points.length; i++) {
                            if (isfind) continue;
                            //unitTest("<br>nofull:px:" + points[i].x + "-py:" + points[i].y);

                            if ((points[i].x >= zerox) && (points[i].y >= zeroy) && (points[i].x <= (zerox + window.screen.availWidth)) && (points[i].y <= (zeroy + window.screen.availHeight))) {
                                target.isview = true;
                                isfind = true; //用break会造成浏览器假死，why？
                                if (target.viewcount == 0) {
                                    target.lasttime = new Date;
                                    target.firsttime = new Date;
                                };
                                target.viewcount++;
                                var currenttime = new Date;
                                target.adTimespan = currenttime.getTime() - target.lasttime.getTime();

                                //alert("px:" + points[i].x + "-py:" + points[i].y + "---zerox:" + zerox + "-zeroy:" + zeroy + "--h:" + (zeroy + window.screen.availHeight));
                                //unitTest("<br>nofull");


                            };
                        };
                    };
                };
            },
            getViewAds: function () {
                var viewads = new Array;
                for (var i = 0; i < advPositionSet.advs.length; i++) {
                    if (advPositionSet.advs[i].isview && advPositionSet.advs[i].adTimespan > 1000)
                        viewads.push(advPositionSet.advs[i]);
                };
                return viewads;
            }
        };
        globalwin.advPositionSet = advPositionSet;
        //需要有外部配置对应参数对象
        var wineventconfig = {
            //鼠标移动、窗体滚动、鼠标点击
            eventitem: [{ name: "scroll", ev: globalwin.advhostpage.pageScroll, isbind: true }, { name: "focus", ev: globalwin.advhostpage.pageFocus, isbind: true}, { name: "blur", ev: globalwin.advhostpage.pageBlur, isbind: true}, { name: "beforeunload", ev: globalwin.advhostpage.pageClose, isbind: true}],
            init: function () {
                var bingStand = win.addEventListener ? true : false;
                for (var i = 0; i < wineventconfig.eventitem.length; i++) {
                    var target = wineventconfig.eventitem[i];
                    //对象结构:autosense_name=true/false
                    if (win["autosenseglobal_" + target.name]) {
                        target.isbind = win["autosenseglobal_" + target.name];
                    };
                    if (target.isbind) {
                        addEvent((bingStand ? "" : "on") + target.name, target.ev);
                    };
                };
                //由于ie与其他浏览器对鼠标mousemove事件支持对象不同，需作特殊处理
                var isbindmousemove = true;
                if (win["autosenseglobal_mousemove"]) {
                    isbindmousemove = win["autosenseglobal_mousemove"];
                };
                var mouseevent = globalwin.advhostpage.getMouseXY;
                if (isbindmousemove) {
                    if (isIE) {
                        if (bingStand) {//ie高版本支持标准绑定
                            dom.addEventListener("mousemove", mouseevent);
                        } else {
                            dom.attachEvent("onmousemove", mouseevent);
                        };
                    } else {
                        win.addEventListener("mousemove", mouseevent);//非ie浏览器均采取标准绑定
                    };
                };
            }
        };
        globalwin.wineventconfig = wineventconfig;
    };
    //--------------------------------临时对象定义区-------------------------------------------     

    //广告位
    var adInfo = {
        advPostionId: "",
        generateId: "",
        advdatas: null,
        heartbeat:true,
        //广告请求参数以及默认值
        requestParamas: [{ name: "unionid", val: "autosense_uid", defaultval: "", isencode: false }, { name: "siteid", val: "autosense_adsiteid", defaultval: "", isencode: false }, { name: "adnum", val: "autosense_adnum", defaultval: "3", isencode: false }, { name: "type", val: "autosense_type", defaultval: "1", isencode: false }, { name: "titlelen", val: "autosense_titlelen", defaultval: "10", isencode: false }, { name: "contentlen", val: "autosense_contentlen", defaultval: "", isencode: false }, { name: "border", val: "autosense_border", defaultval: "", isencode: true }, { name: "width", val: "autosense_width", defaultval: "0", isencode: false }, { name: "height", val: "autosense_height", defaultval: "0", isencode: false }, { name: "headbj", val: "autosense_headbj", defaultval: "", isencode: true }, { name: "arraytype", val: "autosense_arraytype", defaultval: "29", isencode: false }, { name: "contentbj", val: "autosense_contentbj", defaultval: "", isencode: true }, { name: "contenttitle", val: "autosense_contenttitle", defaultval: "", isencode: true }, { name: "contenttext", val: "autosense_contenttext", defaultval: "", isencode: true }, { name: "contentlink", val: "autosense_contentlink", defaultval: "", isencode: true }, { name: "isshowhead", val: "autosense_isshowhead", defaultval: "0", isencode: false }, { name: "cbid", val: "autosense_cbid", defaultval: "", isencode: false }, { name: "cityid", val: "autosense_cityid", defaultval: "", isencode: false }, { name: "mrepeate", val: "autosense_mrepeate", defaultval: "0", isencode: false }],
        //广告位绝对坐标
        x: 0,
        y: 0,
        //加载时间
        adRequestTime: "",
        //加载完成时间
        loadOverTime: "",
        //广告位的元素id
        advdomid: "",
        //广告内容数据的请求来源路径
        advSrc: "",
        //广告位的宽度
        advwidth: 0,
        //广告位的高度
        advheight: 0,
        //广告宿主定义样式
        advstyle: null,
        //广告容器是否显示   
        wrapshow: 1,
        //广告外包元素的宽
        wrapwidth: 0,
        //广告外包元素的高
        wrapheight: 0,
        //容器是否合法，高宽不为0，不隐藏
        wraplegal: 1,
        //容器id
        wrapdomid: "",
        //广告宿主定义模板
        advtemplate: "",
        wraptype: "iframe",//广告的外包类型iframe和ins
        //首次展示时间
        firsttime: null,
        //上一次展示时间
        lasttime: null,
        //上次心跳发送时间
        lastheartsendtime: null,
        //心跳次数
        hearttotal:adHeartTotal,
        viewcount: 0,
        //是否已经展示
        isview: false,
        //是否已经发送了
        issend: false,
        //单位毫秒
        adTimespan: 0,
        //构造后端函数请求地址  
        makeUrl: function () {
            var paramas = adInfo.requestParamas;
            var url = globalwin.nasConfig.urlitem[0].iframeSrc + "?" + "posid=" + adInfo.generateId + "&pageid=" + globalwin.advhostpage.pageid + "&userid=" + globalwin.user.userid + "&referurl=" + globalwin.advhostpage.location;
            for (var i = 0; i < paramas.length; i++) {
                if (!globalwin.advbase.isInstance(globalwin.nasConfig.kv[paramas[i].val]))
                    continue;
                if (paramas[i].isencode)
                    url = url + "&" + paramas[i].name + "=" + encodeURIComponent(globalwin.nasConfig.kv[paramas[i].val] ? globalwin.nasConfig.kv[paramas[i].val] : paramas[i].defaultval);
                else
                    url = url + "&" + paramas[i].name + "=" + (globalwin.nasConfig.kv[paramas[i].val] ? globalwin.nasConfig.kv[paramas[i].val] : paramas[i].defaultval);
            };
            url = url + (adInfo.jumpurl ? "&jumpurl=" + adInfo.jumpurl : "");
            return url;
        },
        //获取坐标，相对于文档的左上角
        getXY: function (domobj) {
            var x = 0, y = 0;
            if (domobj.getBoundingClientRect) {
                var box = domobj.getBoundingClientRect();
                var D = document.documentElement;
                x = box.left + Math.max(D.scrollLeft, document.body.scrollLeft) - D.clientLeft;
                y = box.top + Math.max(D.scrollTop, document.body.scrollTop) - D.clientTop
            }
            else {
                for (; domobj != document.body; x += domobj.offsetLeft, y += domobj.offsetTop, domobj = domobj.offsetParent) { }
            }
            return { x: x, y: y }
        },
        //载入广告位
        iframeloadtest: function (iframeid, callback) {
            var iframeobj = _$(iframeid);
            iframeobj.onload = iframeobj.onreadystatechange = function () {
                if (this.readyState && this.readyState != 'complete') return;
                else {
                    callback();
                }
            }
        },
        loadAdv: function (wrapid) {
            function loadoverevent() {
                adInfo.loadOverTime = new Date();
                var iframeobj = _$(adInfo.advdomid);
                var xy = adInfo.getXY(iframeobj);
                adInfo.x = xy.x;
                adInfo.y = xy.y;
                //var firsturl = globalwin.nasConfig.urlitem[3].firstLoadAdSrc+"?";
                //firsturl = firsturl + "&pageid=" + globalwin.advhostpage.pageid + "&posid=" + adInfo.generateId + "&userid=" + globalwin.user.userid + "&x=" + adInfo.x + "&y=" + adInfo.y +"&ft=" + globalwin.advbase.formatDate(adInfo.adRequestTime) + "&fe=" + globalwin.advbase.formatDate(adInfo.loadOverTime);
                // globalwin.advhostpage.loadJs(firsturl, function () { }, null, scriptId, null);
                //alert("加载完成");
                if (!globalwin.beated) {
                    globalwin.beated = true;
                    heartbeat();

                    //unitTest("<br>2-heartbeat");

                };
                //else
                //{
                //    globalwin.advhostpage.pageHeartbeatStop = false;//重新开始心跳
                //}
            };
            //globalwin.advhostpage.pageHeartbeatStop = true;//将心跳暂停
            ////alert("心跳暂停")
            //setTimeout(function () {//防止请求超时造成心跳死锁,超过2s如果仍未开始，就重新开启心跳
            //    if (globalwin.advhostpage.pageHeartbeatStop)
            //        //alert("重新开始")
            //        globalwin.advhostpage.pageHeartbeatStop = false;//重新开始心跳
            //},2000);
            adInfo.advSrc = adInfo.makeUrl();
            var wrapdomobj = _$(wrapid);
            if (wrapdomobj) {
                var iframeobj = document.createElement("iframe");
                iframeobj.id = adInfo.advdomid;
                iframeobj.name = adInfo.advdomid;
                iframeobj.src = adInfo.advSrc;
                iframeobj.frameborder = 0;
                iframeobj.marginheight = 0;
                iframeobj.marginwidth = 0;
                iframeobj.scrolling = "no";
                iframeobj.width = adInfo.advwidth + "px";
                iframeobj.height = adInfo.advheight + "px";
                var wrapdomcssobj = globalwin.advbase.getComputedStyle(wrapdomobj);
                adInfo.wrapwidth = wrapdomcssobj.width;                
                adInfo.wrapheight = wrapdomcssobj.height;
                adInfo.wrapdomid = wrapid;
                wrapdomobj.appendChild(iframeobj);
                adInfo.adRequestTime = new Date();
                adInfo.iframeloadtest(adInfo.advdomid, loadoverevent);
            }
            else {
                var iframeHtml = '<iframe id="' + adInfo.advdomid + '" name="' + adInfo.advdomid + '" src="' + adInfo.advSrc + '" frameborder="0" marginheight="0" marginwidth="0" scrolling="no" width="' + adInfo.advwidth + 'px" height="' + adInfo.advheight + 'px"></iframe>';
                adInfo.adRequestTime = new Date();
                document.write(iframeHtml);
                adInfo.iframeloadtest(adInfo.advdomid, loadoverevent);
                var domobj = _$(adInfo.advdomid);
                if (domobj.parentNode) {
                    var objstyle = globalwin.advbase.getComputedStyle(domobj.parentNode);
                    adInfo.wrapx = objstyle.width;
                    adInfo.wrapy = objstyle.height;
                    adInfo.wrapdomid = domobj.parentNode.id;
                }
            }
        },
        //检测是否已经展示
        checkwrap: function (domid, advpobj) {
            //判断是否处于iframe中
            if ((dom.parentWindow == self) || (typeof (reValue) == "undefined")) {//ie与firefox兼容
                //不处于iframe中
                if (!_$(domid))
                    advpobj.wraplegal = 0;
            }
            else {
                //处于iframe中
                if (win.innerHeight && win.innerWidth) {
                    if ((win.innerHeigh < 10) || (win.innerWidth < 10))
                        advpobj.wraplegal = 0;
                }
                else {
                    if ((dom.documentElement.clientHeight < 10) || (dom.documentElement.clientHeight < 10))
                        advpobj.wraplegal = 0;
                }
            };
        }
    };
    //---------------------------------------------执行区----------------------------
    generateId = globalwin.advbase.guid();
    posId = posId + generateId;
    scriptId = scriptId + generateId;
    function initcurrentad() {
        globalwin.advhostpage.pageHeart = (globalwin.nasConfig.kv["autosense_pageheart"]) ? globalwin.nasConfig.kv["autosense_pageheart"] : true;     
        adInfo.advdomid = posId;
        adInfo.generateId = generateId;
        adInfo.advPostionId = adInfo.advdomid;
        adInfo.heartbeat = (globalwin.nasConfig.kv["autosense_heartbeat"]) ? globalwin.nasConfig.kv["autosense_heartbeat"] : true;
        adInfo.advheight = globalwin.nasConfig.kv["autosense_height"];
        adInfo.advwidth = globalwin.nasConfig.kv["autosense_width"]; 
        globalwin.advPositionSet.push(adInfo);//需要放在加载之前
    };
    function heartbeat() {
        setTimeout(globalwin.advhostpage.heartbeat, 1000);
    };
    function pageFirstRequest() {
        if (!win["autosenseglobal_pageload"]) {
            return;
        };
        if ((!globalwin.advhostpage.pageRequestInfoSended) && issend) {
            globalwin.advhostpage.pageRequestInfoSended = true;
            globalwin.advhostpage.pageRequest();
        };
    };
    //配置脚本执行过程
    var actionconfig = [{ name: "inituser", ev: globalwin.user.inituser, isaction: true }, { name: "pageload", ev: pageFirstRequest, isaction: true }, { name: "initadconfig", ev: globalwin.nasConfig.loadConfig, isaction: true }, { name: "initad", ev: initcurrentad, isaction: true }, { name: "loadad", ev: adInfo.loadAdv, isaction: true }, { name: "bindEvent", ev: globalwin.wineventconfig.init, isaction: true }];
    //执行
    for (var runindex = 0; runindex < actionconfig.length; runindex++) {
        if (actionconfig[runindex].isaction)
            actionconfig[runindex].ev();
    };
})(window, bitadv);


